package com.project.aspect;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.io.Reader;
import java.lang.reflect.Field;

@Service
@Aspect
public class ServiceAspect {
    public static SqlSessionFactory factory;
    static {
        try {
            Reader r = Resources.getResourceAsReader("mybatis.cfg.xml");
            factory = new SqlSessionFactoryBuilder().build(r);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Around("execution(* com.project.service..*.*(..))")
    public Object around(ProceedingJoinPoint jp){
        SqlSession session =factory.openSession();
        try {
//            //得到代理的目标对象
//            Object targetObj = jp.getTarget();
//            //得到属性列表
//            Field[] fieldArray = targetObj.getClass().getFields();
//            for (int i = 0; i < fieldArray.length; i++) {
//                if (fieldArray[i].getType().isInterface()) {
//                    fieldArray[i].setAccessible(true);
//                    //得到mapper接口实现类对象
//                    Object mapperObj = session.getMapper(fieldArray[i].getType());
//                    fieldArray[i].set(targetObj,mapperObj);
//                }
//            }

            //得到目标对象
            Object targetObj = jp.getTarget();
            //得到属性列表
            Field[] fieldArray = targetObj.getClass().getDeclaredFields();
            for(Field f : fieldArray){
                //判断该属性是否为接口
                if(f.getType().isInterface()){
                    f.setAccessible(true);
                    //得到mapper接口实现类对象
                    Object mapperObj = session.getMapper(f.getType());
                    //设置该属性的实现类对象
                    f.set(targetObj,mapperObj);
                }
            }
//            执行目标方法，得到方法执行后的返回值
            Object returnObj = jp.proceed();
            //提交事务
            session.commit();
            return returnObj;
        }catch (Throwable e){
            e.printStackTrace();
            session.rollback();
        }finally {
            session.close();
        }
        return null;
    }
}
